// miniprogram/pages/addOrEdit/addOrEdit.js

const app = getApp()

Page({
  data: {
    disabled: false,
    category: '',
    products: '',
    id: '',
    required: false
  },

  onLoad: function (options) {
    console.log(options)
    if (app.globalData.openid) {
      this.setData({
        openid: app.globalData.openid
      })
    }
    if (options.id) {
      this.setData({
        id: options.id
      })
      this.onQuery(options.id);
    }
  },

  // 查询
  onQuery: function (id) {
    const db = wx.cloud.database();
    db.collection('categories').where({
      _id: id
    }).get({
      success: res => {
        this.setData({
          category: res.data[0].category,
          products: res.data[0].products,
        })
        console.log('[数据库] [查询记录] 成功: ', res)
      },
      fail: err => {
        wx.showToast({
          icon: 'none',
          title: '查询记录失败'
        })
        console.error('[数据库] [查询记录] 失败：', err)
      }
    })
  },

  // 更新
  updateCategory() {
    const db = wx.cloud.database();
    db.collection('categories').doc(this.data.id).update({
      data: {
        category: this.data.category,
        products: this.data.products
      },
      success: res => {
        wx.showToast({
          title: '更新记录成功',
        })
        this.setData({
          categoryId: res._id,
        })
        setTimeout(() => {
          wx.switchTab({ url: '/pages/list/list' });
        }, 300)
      },
      fail: err => {
        icon: 'none',
          console.error('[数据库] [更新记录] 失败：', err)
      },
      complete: () => {
        this.setData({
          disabled: false
        })
      }
    })
  },

  // 新增
  addCategory() {
    const db = wx.cloud.database();
    db.collection('categories').add({
      data: {
        category: this.data.category,
        products: this.data.products
      },
      success: res => {
        wx.showToast({
          title: '新增记录成功',
        })
        this.setData({
          categoryId: res._id,
        })
        setTimeout(() => {
          wx.switchTab({ url: '/pages/list/list' });
        }, 300)
      },
      fail: err => {
        wx.showToast({
          icon: 'none',
          title: '新增记录失败'
        })
        console.error('[数据库] [新增记录] 失败：', err);
      },
      complete: () => {
        this.setData({
          disabled: false
        })
      }
    });
  },

  formSubmit(e) {
    if(!e.detail.value.category || !e.detail.value.products) {
      this.setData({
        required: true
      })

      setTimeout(() => {
        this.setData({
          required: false
        })
      }, 3000);
      return;
    }
    let products = e.detail.value.products
      .replace(/(^,*)|(,*$)|(^，*)|(，*$)/g, '')
      .replace(/[,|，]/g, ',');
    this.setData({
      category: e.detail.value.category,
      products: products.split(','),
      disabled: true
    })
    if(this.data.id) {
      this.updateCategory();
      return;
    }
    this.addCategory()
  }
})